<template>
  <div class="icloud-container">
    <!-- 左侧边栏 -->
    <div class="icloud-sidebar">
      <div class="sidebar-header">
        <h2>iCloud</h2>
      </div>

      <div class="sidebar-content">
        <!-- 收藏夹 -->
        <div class="sidebar-section">
          <div class="section-title">收藏夹</div>
          <div
            class="sidebar-item"
            :class="{ active: currentView === 'favorites' }"
            @click="currentView = 'favorites'"
          >
            <span class="item-icon">⭐</span>
            <span class="item-name">收藏</span>
          </div>
        </div>

        <!-- iCloud -->
        <div class="sidebar-section">
          <div class="section-title">iCloud</div>
          <div
            class="sidebar-item"
            :class="{ active: currentView === 'drive' }"
            @click="currentView = 'drive'"
          >
            <span class="item-icon">☁️</span>
            <span class="item-name">iCloud Drive</span>
          </div>
          <div
            class="sidebar-item"
            :class="{ active: currentView === 'shared' }"
            @click="currentView = 'shared'"
          >
            <span class="item-icon">👥</span>
            <span class="item-name">共享</span>
          </div>
        </div>

        <!-- 最近使用 -->
        <div class="sidebar-section">
          <div class="section-title">标签</div>
          <div
            class="sidebar-item"
            :class="{ active: currentView === 'recent' }"
            @click="currentView = 'recent'"
          >
            <span class="item-icon">🕐</span>
            <span class="item-name">最近使用</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="icloud-main">
      <!-- 顶部工具栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <button class="toolbar-btn icon-btn" @click="showNewFolderDialog = true" title="新建文件夹">
            <span class="btn-icon">📁</span>
          </button>
          <button class="toolbar-btn icon-btn" @click="handleUpload" title="上传">
            <span class="btn-icon">⬆️</span>
          </button>
        </div>

        <div class="toolbar-center">
          <input
            type="text"
            class="search-input"
            v-model="icloudStore.searchQuery"
            placeholder="搜索 iCloud Drive"
          >
        </div>

        <div class="toolbar-right">
          <button
            class="view-btn"
            :class="{ active: icloudStore.viewMode === 'grid' }"
            @click="icloudStore.setViewMode('grid')"
            title="网格视图"
          >
            ⊞
          </button>
          <button
            class="view-btn"
            :class="{ active: icloudStore.viewMode === 'list' }"
            @click="icloudStore.setViewMode('list')"
            title="列表视图"
          >
            ☰
          </button>
        </div>
      </div>

      <!-- 文件区域 -->
      <div class="files-container" :class="icloudStore.viewMode">
        <!-- 网格视图 -->
        <div v-if="icloudStore.viewMode === 'grid'" class="grid-view">
          <div
            v-for="file in filteredFiles"
            :key="file.id"
            class="file-item"
            :class="{ selected: icloudStore.selectedFiles.includes(file.id) }"
            @click="toggleSelection(file.id)"
            @dblclick="handleFileDoubleClick(file)"
            @contextmenu.prevent="showContextMenu($event, file)"
          >
            <div class="file-icon-wrapper">
              <div class="file-icon">{{ file.icon }}</div>
              <div v-if="file.isFavorite" class="favorite-badge">⭐</div>
              <div v-if="file.isShared" class="shared-badge">👥</div>
            </div>
            <div class="file-name">{{ file.name }}</div>
          </div>
        </div>

        <!-- 列表视图 -->
        <div v-else class="list-view">
          <table class="files-table">
            <thead>
              <tr>
                <th class="col-name">名称</th>
                <th class="col-modified">修改日期</th>
                <th class="col-size">大小</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="file in filteredFiles"
                :key="file.id"
                class="file-row"
                :class="{ selected: icloudStore.selectedFiles.includes(file.id) }"
                @click="toggleSelection(file.id)"
                @dblclick="handleFileDoubleClick(file)"
                @contextmenu.prevent="showContextMenu($event, file)"
              >
                <td class="col-name">
                  <span class="file-icon-small">{{ file.icon }}</span>
                  <span>{{ file.name }}</span>
                  <span v-if="file.isFavorite" class="badge">⭐</span>
                  <span v-if="file.isShared" class="badge">👥</span>
                </td>
                <td class="col-modified">{{ formatDate(file.modifiedTime) }}</td>
                <td class="col-size">{{ file.type === 'folder' ? '-' : icloudStore.formatFileSize(file.size) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 底部状态栏 -->
      <div class="status-bar">
        <div class="status-left">
          <span>{{ filteredFiles.length }} 个项目</span>
          <span v-if="icloudStore.selectedFiles.length > 0"> · {{ icloudStore.selectedFiles.length }} 个已选中</span>
        </div>
        <div class="status-right">
          <div class="storage-info">
            <div class="storage-bar">
              <div
                class="storage-used"
                :style="{ width: storagePercent + '%' }"
              ></div>
            </div>
            <span class="storage-text">
              {{ icloudStore.storageUsed }} GB / {{ icloudStore.storageTotal }} GB 已用
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 新建文件夹对话框 -->
    <div v-if="showNewFolderDialog" class="dialog-overlay" @click="showNewFolderDialog = false">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>新建文件夹</h3>
        </div>
        <div class="dialog-body">
          <input
            type="text"
            class="dialog-input"
            v-model="newFolderName"
            placeholder="未命名文件夹"
            @keyup.enter="createFolder"
          >
        </div>
        <div class="dialog-footer">
          <button class="dialog-btn cancel" @click="showNewFolderDialog = false">取消</button>
          <button class="dialog-btn primary" @click="createFolder">创建</button>
        </div>
      </div>
    </div>

    <!-- 右键菜单 -->
    <transition name="context-menu-fade">
      <div
        v-if="contextMenu.show"
        class="context-menu"
        :style="{ left: contextMenu.x + 'px', top: contextMenu.y + 'px' }"
        @click.stop
      >
        <div class="context-menu-item" @click="handleToggleFavorite">
          {{ contextMenu.file?.isFavorite ? '从收藏中移除' : '添加到收藏' }}
        </div>
        <div class="context-menu-item" @click="handleToggleShare">
          {{ contextMenu.file?.isShared ? '停止共享' : '共享...' }}
        </div>
        <div class="context-menu-divider"></div>
        <div class="context-menu-item" @click="handleRename">重命名</div>
        <div class="context-menu-divider"></div>
        <div class="context-menu-item danger" @click="handleDelete">删除</div>
      </div>
    </transition>

    <div v-if="contextMenu.show" class="context-menu-overlay" @click="closeContextMenu"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useICloudStore, type iCloudFile } from '@/stores/icloud.ts'

const icloudStore = useICloudStore()

const currentView = ref<'drive' | 'favorites' | 'shared' | 'recent'>('drive')
const showNewFolderDialog = ref(false)
const newFolderName = ref('')

const contextMenu = ref({
  show: false,
  x: 0,
  y: 0,
  file: null as iCloudFile | null
})

// 筛选文件
const filteredFiles = computed(() => {
  let files = icloudStore.files

  // 根据视图筛选
  if (currentView.value === 'favorites') {
    files = files.filter(f => f.isFavorite)
  } else if (currentView.value === 'shared') {
    files = files.filter(f => f.isShared)
  } else if (currentView.value === 'recent') {
    files = [...files].sort((a, b) => b.modifiedTime.getTime() - a.modifiedTime.getTime()).slice(0, 20)
  }

  // 搜索筛选
  if (icloudStore.searchQuery) {
    files = files.filter(f =>
      f.name.toLowerCase().includes(icloudStore.searchQuery.toLowerCase())
    )
  }

  return files
})

// 存储使用百分比
const storagePercent = computed(() => {
  return (icloudStore.storageUsed / icloudStore.storageTotal) * 100
})

// 格式化日期
function formatDate(date: Date): string {
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (days === 0) return '今天'
  if (days === 1) return '昨天'
  if (days < 7) return `${days} 天前`

  return date.toLocaleDateString('zh-CN', { month: 'long', day: 'numeric' })
}

// 切换选择
function toggleSelection(fileId: string) {
  if (icloudStore.selectedFiles.includes(fileId)) {
    icloudStore.deselectFile(fileId)
  } else {
    icloudStore.selectFile(fileId)
  }
}

// 双击文件
function handleFileDoubleClick(file: iCloudFile) {
  if (file.type === 'folder') {
    // 进入文件夹
    console.log('进入文件夹:', file.name)
  } else {
    // 打开文件
    console.log('打开文件:', file.name)
  }
}

// 创建文件夹
function createFolder() {
  if (!newFolderName.value.trim()) {
    newFolderName.value = '未命名文件夹'
  }

  icloudStore.addFile({
    name: newFolderName.value,
    type: 'folder',
    modifiedTime: new Date(),
    icon: '📁'
  })

  showNewFolderDialog.value = false
  newFolderName.value = ''
}

// 上传文件
function handleUpload() {
  // 模拟上传
  icloudStore.addFile({
    name: `新文件_${Date.now()}.txt`,
    type: 'file',
    size: Math.floor(Math.random() * 1000000),
    modifiedTime: new Date(),
    icon: '📄'
  })
}

// 显示右键菜单
function showContextMenu(event: MouseEvent, file: iCloudFile) {
  contextMenu.value = {
    show: true,
    x: event.clientX,
    y: event.clientY,
    file
  }
}

// 关闭右键菜单
function closeContextMenu() {
  contextMenu.value.show = false
}

// 切换收藏
function handleToggleFavorite() {
  if (contextMenu.value.file) {
    icloudStore.toggleFavorite(contextMenu.value.file.id)
  }
  closeContextMenu()
}

// 切换共享
function handleToggleShare() {
  if (contextMenu.value.file) {
    icloudStore.toggleShare(contextMenu.value.file.id)
  }
  closeContextMenu()
}

// 重命名
function handleRename() {
  if (contextMenu.value.file) {
    const newName = prompt('请输入新名称:', contextMenu.value.file.name)
    if (newName && newName.trim()) {
      icloudStore.renameFile(contextMenu.value.file.id, newName.trim())
    }
  }
  closeContextMenu()
}

// 删除
function handleDelete() {
  if (contextMenu.value.file) {
    if (confirm(`确定要删除"${contextMenu.value.file.name}"吗？`)) {
      icloudStore.deleteFile(contextMenu.value.file.id)
    }
  }
  closeContextMenu()
}
</script>

<style scoped>
.icloud-container {
  display: flex;
  height: 100%;
  background: #f5f5f7;
  overflow: hidden;
}

/* 左侧边栏 */
.icloud-sidebar {
  width: 200px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  border-right: 1px solid rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 48px 16px 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.sidebar-header h2 {
  font-size: 20px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0;
}

.sidebar-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.sidebar-section {
  margin-bottom: 16px;
}

.section-title {
  padding: 8px 16px 4px;
  font-size: 11px;
  font-weight: 600;
  color: #86868b;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.sidebar-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 16px;
  margin: 0 8px;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.2s;
  font-size: 13px;
  color: #1d1d1f;
}

.sidebar-item:hover {
  background: rgba(0, 0, 0, 0.05);
}

.sidebar-item.active {
  background: #007aff;
  color: white;
}

.item-icon {
  font-size: 16px;
}

.item-name {
  flex: 1;
}

/* 主内容区 */
.icloud-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #ffffff;
}

/* 工具栏 */
.toolbar {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 48px 20px 12px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.toolbar-center {
  flex: 1;
  max-width: 400px;
}

.toolbar-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 6px 12px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  background: white;
  font-size: 13px;
  color: #1d1d1f;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
  position: relative;
}

.toolbar-btn.icon-btn {
  padding: 8px;
  width: 36px;
  height: 36px;
}

.btn-icon {
  font-size: 18px;
}

.toolbar-btn:hover {
  background: rgba(0, 0, 0, 0.05);
  border-color: rgba(0, 0, 0, 0.2);
}

/* Tooltip效果 */
.toolbar-btn::after {
  content: attr(title);
  position: absolute;
  bottom: calc(100% + 8px);
  left: 50%;
  transform: translateX(-50%);
  padding: 4px 10px;
  background: rgba(50, 50, 50, 0.9);
  backdrop-filter: blur(20px);
  color: white;
  font-size: 12px;
  border-radius: 6px;
  white-space: nowrap;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  z-index: 1000;
}

.toolbar-btn:hover::after {
  opacity: 1;
}

.search-input {
  width: 100%;
  padding: 8px 12px;
  border: 0.5px solid rgba(0, 0, 0, 0.12);
  border-radius: 8px;
  font-size: 13px;
  background: rgba(255, 255, 255, 0.6);
  box-shadow:
    0 1px 2px rgba(0, 0, 0, 0.08),
    0 0 0 0.5px rgba(255, 255, 255, 0.5) inset;
  transition:
    border-color 0.25s cubic-bezier(0.4, 0, 0.2, 1),
    box-shadow 0.25s cubic-bezier(0.4, 0, 0.2, 1),
    background-color 0.2s cubic-bezier(0.4, 0, 0.2, 1),
    transform 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.search-input:hover:not(:focus) {
  background: rgba(255, 255, 255, 0.75);
  border-color: rgba(0, 0, 0, 0.2);
  box-shadow:
    0 2px 4px rgba(0, 0, 0, 0.1),
    0 0 0 0.5px rgba(255, 255, 255, 0.6) inset;
}

.search-input:focus {
  outline: none;
  border-color: #007AFF;
  background: rgba(255, 255, 255, 0.95);
  box-shadow:
    0 0 0 3.5px rgba(0, 122, 255, 0.15),
    0 2px 6px rgba(0, 0, 0, 0.1),
    0 0 0 0.5px #007AFF inset;
  transform: translateY(-1px);
}

.view-btn {
  width: 32px;
  height: 32px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  background: white;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.2s;
}

.view-btn:hover {
  background: rgba(0, 0, 0, 0.05);
}

.view-btn.active {
  background: #007aff;
  color: white;
  border-color: #007aff;
}

/* 文件区域 */
.files-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

/* 网格视图 */
.grid-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 16px;
}

.file-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.file-item:hover {
  background: rgba(0, 0, 0, 0.04);
}

.file-item.selected {
  background: rgba(0, 122, 255, 0.15);
  border: 2px solid #007aff;
}

.file-icon-wrapper {
  position: relative;
  margin-bottom: 8px;
}

.file-icon {
  font-size: 48px;
}

.favorite-badge,
.shared-badge {
  position: absolute;
  top: -4px;
  right: -4px;
  font-size: 14px;
  background: white;
  border-radius: 50%;
  padding: 2px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.shared-badge {
  top: auto;
  bottom: -4px;
}

.file-name {
  font-size: 12px;
  text-align: center;
  word-break: break-word;
  max-width: 100%;
  color: #1d1d1f;
}

/* 列表视图 */
.list-view {
  width: 100%;
}

.files-table {
  width: 100%;
  border-collapse: collapse;
}

.files-table thead {
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.files-table th {
  padding: 8px 12px;
  text-align: left;
  font-size: 12px;
  font-weight: 600;
  color: #86868b;
}

.file-row {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: background 0.2s;
}

.file-row:hover {
  background: rgba(0, 0, 0, 0.03);
}

.file-row.selected {
  background: rgba(0, 122, 255, 0.1);
}

.file-row td {
  padding: 8px 12px;
  font-size: 13px;
  color: #1d1d1f;
}

.col-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-icon-small {
  font-size: 18px;
}

.badge {
  font-size: 12px;
  margin-left: 4px;
}

.col-modified,
.col-size {
  color: #86868b;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 20px;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  font-size: 12px;
  color: #86868b;
}

.storage-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.storage-bar {
  width: 100px;
  height: 4px;
  background: rgba(0, 0, 0, 0.1);
  border-radius: 2px;
  overflow: hidden;
}

.storage-used {
  height: 100%;
  background: linear-gradient(90deg, #007aff, #0051d5);
  transition: width 0.3s;
}

/* 对话框 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  width: 400px;
  max-width: 90vw;
}

.dialog-header {
  padding: 20px 20px 12px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.dialog-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1d1d1f;
}

.dialog-body {
  padding: 20px;
}

.dialog-input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid rgba(0, 0, 0, 0.2);
  border-radius: 6px;
  font-size: 14px;
}

.dialog-input:focus {
  outline: none;
  border-color: #007aff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 12px 20px 20px;
}

.dialog-btn {
  padding: 8px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.dialog-btn.cancel {
  background: transparent;
  border: 1px solid rgba(0, 0, 0, 0.2);
  color: #1d1d1f;
}

.dialog-btn.cancel:hover {
  background: rgba(0, 0, 0, 0.05);
}

.dialog-btn.primary {
  background: #007aff;
  border: none;
  color: white;
}

.dialog-btn.primary:hover {
  background: #0051d5;
}

/* 右键菜单 */
.context-menu-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 998;
}

.context-menu {
  position: fixed;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(40px);
  border-radius: 8px;
  padding: 4px;
  z-index: 999;
  min-width: 180px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.context-menu-item {
  padding: 8px 12px;
  font-size: 13px;
  color: #1d1d1f;
  cursor: pointer;
  border-radius: 4px;
  transition: background 0.2s;
}

.context-menu-item:hover {
  background: rgba(0, 122, 255, 0.1);
}

.context-menu-item.danger {
  color: #ff3b30;
}

.context-menu-divider {
  height: 1px;
  background: rgba(0, 0, 0, 0.1);
  margin: 4px 0;
}

.context-menu-fade-enter-active,
.context-menu-fade-leave-active {
  transition: all 0.2s;
}

.context-menu-fade-enter-from {
  opacity: 0;
  transform: scale(0.95);
}

.context-menu-fade-leave-to {
  opacity: 0;
  transform: scale(0.98);
}

/* 响应式 */
@media (max-width: 768px) {
  .icloud-sidebar {
    width: 60px;
  }

  .sidebar-header h2,
  .section-title,
  .item-name {
    display: none;
  }

  .toolbar {
    flex-wrap: wrap;
  }

  .toolbar-center {
    order: 3;
    flex-basis: 100%;
    max-width: 100%;
  }

  .grid-view {
    grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  }
}
</style>

